# -*- coding: utf-8 -*-
import datetime

from flask import Blueprint, render_template, request, url_for, redirect, jsonify

from application import db
from common.libs.UserSerivice import UserService
from web.models.AppAccessLog import AppAccessLog
from web.models.user import User

route_account = Blueprint('account_page', __name__)


@route_account.route("/index")
def index():
    """展示账号列表"""
    # 查询所有账号
    user_list = User.query.all()
    # user_list = None
    context = {
        'user_list': user_list
    }
    return render_template("account/index.html", **context)


@route_account.route("/info")
def info():
    """查看某个账号详情"""
    # 取得账号id
    context = {}
    req = request.values
    uid = int(req.get("id", 0))
    reback_url = url_for('account_page.index')
    if uid < 1:
        return redirect(reback_url)
    info = User.query.filter_by(uid=uid).first()
    if not info:
        return redirect(reback_url)
    context["info"] = info
    # 获取当前用户的访问日志
    access_log_list = AppAccessLog.query.filter_by(uid=info.uid).all()
    context["access_log_list"] = access_log_list
    return render_template("account/info.html", **context)


@route_account.route("/set", methods=["GET", "POST"])
def set():
    """新增或者修改账号"""
    resp = {"code": 200, "msg": "操作成功", "data": {}}
    if request.method == "GET":
        context = {}
        req = request.args
        uid = int(req.get("id", 0))
        info = None
        if uid:
            """表示uid有具体的值，表示编辑"""
            info = User.query.filter_by(uid=uid).first()
        context["info"] = info
        return render_template("account/set.html", **context)
    elif request.method == "POST":
        # 1.取得用户传递过来的新增数据
        req = request.values
        nickname = req["nickname"] if "nickname" in req else ""
        mobile = req["mobile"] if "mobile" in req else ""
        email = req["email"] if "email" in req else ""
        login_name = req["login_name"] if "login_name" in req else ""
        login_pwd = req["login_pwd"] if "login_pwd" in req else ""
        id = req["id"] if "id" in req else 0
        # 2.检验账号是否已经注册
        # 验证登录名是否被注册 在添加账号时，User.uid != id才会成立
        has_in = User.query.filter(User.login_name == login_name, User.uid != id).first()
        # has_in = User.query.filter(User.login_name == login_name).first()
        if has_in:
            resp["code"] = -1
            resp["msg"] = "该登录名已经存在，请换一个试一试 "
            return jsonify(resp)
        # 3.取得或者构建一个账号对象，并且赋值
        # 修改or新增账号？
        user_info = User.query.filter_by(uid=id).first()
        if user_info:  # 有值，不为空，则为修改账号
            # 如果admin账号，不允许修改
            if user_info and user_info.uid == 1:
                resp["code"] = -1
                resp["msg"] = "该用户是admin账号，不允许修改编辑 "
                return jsonify(resp)
            model_user = user_info  # 从数据库查询到的账号对象给model_user赋值
        else:  # user_info为空就是新增账号请求
            model_user = User()  # 新建一个User实例
            model_user.login_salt = UserService.genSalt(16)  # 自动产生一个加盐数据，加密密钥，创建用户时生成
            model_user.created_time = datetime.datetime.now()

        # 修改密码：
        if login_pwd != '******':  # 表示修改了密码 重新生成密码保存，要结合前端的密码默认值比较
            model_user.login_pwd = UserService.genPwd(login_pwd, model_user.login_salt)
        # 不管是新增还是编辑 共同的操作
        model_user.nickname = nickname
        model_user.mobile = mobile
        model_user.email = email
        model_user.login_name = login_name
        model_user.updated_time = datetime.datetime.now()

        # 4.提交到数据库中，实现新增
        # resp = {"code": 200, "msg": "操作成功", "data": {}}
        db.session.add(model_user)
        db.session.commit()
        return jsonify(resp)
    else:
        resp['code'] = -1
        resp['msg'] = "请求方式有误"
        return jsonify(resp)


@route_account.route('/ops', methods=['POST'])
def ops():
    resp = {"code": 200, "msg": "操作成功", "data": {}}
    req = request.values
    act = req["act"] if "act" in req else ""
    id = req["id"] if "id" in req else 0
    print('获取到的数据:', act, id)
    if act not in ["remove", "recover"]:
        resp["code"] = -1
        resp["msg"] = "操作有误"
        return jsonify(resp)
    if not id:
        resp["code"] = -1
        resp["msg"] = "请选择要操作的账号"
        return jsonify(resp)
    # 查找要操作的账号
    user_info = User.query.filter_by(uid=id).first()
    if not user_info:
        resp["code"] = -1
        resp["msg"] = "指定账号不存在"
        return jsonify(resp)
    if user_info and user_info.uid == 1:
        resp["code"] = -1
        resp["msg"] = "该用户是admin账号，不允许删除 "
        return jsonify(resp)
    if act == "remove":
        user_info.status = 0  # 删除状态
    elif act == "recover":  # 变成不删除状态
        user_info.status = 1
    user_info.updated_time = datetime.datetime.now()
    db.session.add(user_info)
    db.session.commit()
    return jsonify(resp)
